import http from './http.js'
import { Toast } from 'vant'

export default class BaseApi {
  constructor(domain = '') {
    this.domain = domain
  }

  preRequest (options) {
    return options
  }

  postRequest ({ errno, error, data, total, errmsg }) {
    if (parseInt(errno) === 0) {
      return { data, total, errno }
    } else if (parseInt(error) === 0) {
      return { data, total, error }
    } else {
      throw new Error(errno + ':' + errmsg)
    }
  }

  async request (method, url, options, errorMessage, silence) {
    let target = url
    if (url.indexOf('//') > -1) {

    } else if (!/^http?/.test(url)) {
      target = this.domain + url
    }
    options = this.preRequest(options, url)
    try {
      let { data, headers } = await http.request(method, target, options)
      return this.postRequest(data, url, headers)
    } catch (e) {
      Toast('请求失败')
    }
  }

  httpGet (url, query, headers, errorMessage, silence) {
    return this.request('get', url, { query, headers }, errorMessage, silence)
  }

  httpPost (url, body, query, errorMessage, silence) {
    return this.request('post', url, { query, body }, errorMessage, silence)
  }

  httpPut (url, body, query, errorMessage, silence) {
    return this.request('put', url, { query, body }, errorMessage, silence)
  }

  httpPatch (url, body, query, errorMessage, silence) {
    return this.request('patch', url, { query, body }, errorMessage, silence)
  }

  httpDelete (url, query, errorMessage, silence) {
    return this.request('delete', url, { query }, errorMessage, silence)
  }
}
